//
//  WBAuthViewController.swift
//  新浪微博
//
//  Created by 名品导购网MPLife.com on 2017/11/28.
//  Copyright © 2017年 sweet. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBAuthViewController: UIViewController {

private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        view .backgroundColor = UIColor .white
        //取消滚动 新浪微博的服务器，返回的授权页面默认是手机全屏
        webView .scrollView .isScrollEnabled = false
       //设置代理
        webView.delegate = self
        title = "登录新浪微博"
        navigationItem .leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(close), isBack: true)
        navigationItem .rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectUrl)"
        //确定要访问的url
        guard let url = URL(string: urlString) else {
            return
        }
        //建立请求
     let request = URLRequest(url: url)
        //加载请求
        webView .loadRequest(request)
    }

    @objc private func close(){
        SVProgressHUD .dismiss()
        self .dismiss(animated: true, completion: nil)
    }
    //自动填充，webViw的注入 直接通过js修改本地的浏览器中缓存的页面内容
    //点击登录按钮，执行submit将本地的数据提交给服务器
    @objc private func autoFill(){
        let js = "document.getElementById('userId').value = '18392130535';" + "document.getElementById('passwd').value = 'GqjGfj0316.wb';"
        webView .stringByEvaluatingJavaScript(from: js)
    }

}
extension WBAuthViewController:UIWebViewDelegate{
    //webView将要加载请求
    //webview
    //要加载的请求
    //导航类型
    //returns是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果请求地址包含http://baidu.com不加载页面/否则加载页面
        if request.url?.absoluteString.hasPrefix(WBRedirectUrl) == false {
            return true
        }
        
//        print("加载请求\(String(describing: request.url?.absoluteString))")
        //query是URL种？后面的所有部分
//        print("加载请求Url\(String(describing: request.url?.query))")
        //2.conghttp://baidu.com回调地址的查询字符串中查找'code='
        //如果有code授权成功，否则授权失败
        if request.url?.query?.hasPrefix("code=") == false{
            //查询字符串不包含code
            print("取消授权")
            close()
            return false
        }
        //从query字符串中取出授权码
        //代码走到此处 url中一定有查询字符串，并且包含code
//        链接地址code=7c864bc6e89bb672742382ded546a6a3
//        获取授权码code
        let urlStr = request.url?.query ?? ""
        let subStr = urlStr.index("=".endIndex, offsetBy: 4)
        let code = urlStr[subStr...]
        print("获取授权码\(code)")
        //使用授权码获取AccessToken
        WBNetworkManager .shared .loadAccessToken(code: String(code))
        return false
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
      SVProgressHUD .show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
      SVProgressHUD .dismiss()
    }
}
